package com.yonyou.ucf.mdf.app.isvdxq.other.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.gson.Gson;
import com.yonyou.ucf.mdf.app.isvdxq.common.ApiYon;
import com.yonyou.ucf.mdf.app.isvdxq.other.mapper.impl.ManageClassMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.yonyisv.model.EventContent;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.ManageClassEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.AccessTokenResponse;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.ContentBean;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.ManageClassBean;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.ManageClassBeanTree;
import com.yonyou.ucf.mdf.app.isvdxq.utils.GenericResponse;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;


@Service
public class ManageClassService {
    @Autowired
    private BaseService baseService;
    @Autowired
    private ManageClassMapperImpl manageClassMapper;

    public ManageClassEntity SelectById(Long Id) {
        return manageClassMapper.selectById(Id);
    }

    public Boolean CheckEntity(Long Id) {
        int rInt = manageClassMapper.selectCount(Id);
        if (rInt > 0) return true;
        else return false;
    }

    public Integer InsertEntity(ManageClassEntity entity) {
        return manageClassMapper.insert(entity);
    }

    public Integer UpdateEntity(ManageClassEntity entity) {
        return manageClassMapper.updateByPrimaryKey(entity);
    }

    public List<ManageClassEntity> SelectAll(String tenantId) {
        return manageClassMapper.selectAll(tenantId);
    }

    public Integer DeleteById(Long Id) {
        return manageClassMapper.deleteByPrimaryKey(Id);
    }

    //新增并更新
    public Integer InsertBatch(List<ManageClassEntity> list) {
        if (list.size() == 0) return 0;
        long start = System.currentTimeMillis();
        int res = manageClassMapper.insertBatch(list);
        long end = System.currentTimeMillis();
        System.out.println("---------------" + (start - end) + "---------------");
        return res;
    }

    //模板单位数据加载同步
    public void EventManageClassEdit(String detailId, String tenantId) throws IOException {
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);

        String requrl = gatewayUrl + ApiYon.getManageclassDetail;
        Map<String, String> params = new HashMap<>();
        if (detailId.equals("")) return;
        // 除签名外的其他参数
        params.put("access_token", token);
        params.put("id", detailId);
        String resString = RequestTool.doGet(requrl, params);
        GenericResponse<ManageClassBean> response = RequestTool.getBean(resString, new TypeReference<GenericResponse<ManageClassBean>>() {
        });
        if (!response.getCode().equals("200")) {
            throw new RuntimeException(resString);
        }
        if (response.getCode().equals("200")) {
            ManageClassBean myDataManageClass = response.getData();
            if (myDataManageClass != null && myDataManageClass.getId() > 0) {
                ManageClassEntity entity = MyTool.convertBean2Bean(myDataManageClass, ManageClassEntity.class);
                entity.setTenant_id(tenantId);
                boolean flagNext = CheckEntity(entity.getId());
                int rInt = 0;
                if (flagNext) {
                    rInt = UpdateEntity(entity);
                } else {
                    rInt = InsertEntity(entity);
                }
                System.out.println("EventManageClassEdit影响条数" + rInt);
            }
        }
    }

    public Integer EventEdit(EventContent content) throws IOException {
        System.out.println(content.getContent());
        ContentBean obj = RequestTool.getBean(content.getContent(), ContentBean.class);
        String tenantId = obj.getTenantId();
        String jsonString = obj.getArchive().replace("detail!id", "detailid").replace("detail!", "");
        ManageClassBean manageClassBean = RequestTool.getBean(jsonString, ManageClassBean.class);
        String jsonStr = new Gson().toJson(manageClassBean);
        ManageClassEntity manageClassEntity = RequestTool.getBean(jsonStr, ManageClassEntity.class);
        manageClassEntity.setTenant_id(tenantId);
        System.out.println(JSON.toJSONString(manageClassEntity));
        Boolean flag = CheckEntity(manageClassEntity.getId());
        if (flag) {
            int rInt = UpdateEntity(manageClassEntity);
            return rInt;
        } else {
            int rInt = InsertEntity(manageClassEntity);
            return rInt;
        }
    }

    public Integer EventDel(EventContent content) throws IOException {
        System.out.println(content.getContent());
        ContentBean obj = RequestTool.getBean(content.getContent(), ContentBean.class);
        Long Id = Long.parseLong(obj.getId());
        Boolean flag = CheckEntity(Id);
        if (flag) {
            int rInt = DeleteById(Id);
            return rInt;
        }
        return 0;
    }


    //模板单位数据加载同步
    public void EventManageClassEditTree(String detailId, String tenantId) throws IOException {
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);

        String requrl = gatewayUrl + ApiYon.getManageclassTree + "?access_token=" + token;
        Map<String, Object> tempparams = new HashMap<>();
        tempparams.put("isExtend", true);
        // 除签名外的其他参数
        if (StringUtils.isNotEmpty(detailId)) {
            List<String> ids = new ArrayList<>();
            ids = Arrays.asList(detailId.split(","));
            Map<String, Object> params_sub = new HashMap<>();
            params_sub.put("field", "code");
            params_sub.put("op", "in");
            params_sub.put("value1", ids);
            tempparams.put("simpleVOs", params_sub);
        }
        Map<String, Object> params = new HashMap<>();
        params.put("condition", tempparams);
        String resString = RequestTool.doPost(requrl, JSONObject.toJSONString(params));
        GenericResponse<List<ManageClassBeanTree>> response = RequestTool.getBean(resString, new TypeReference<GenericResponse<List<ManageClassBeanTree>>>() {
        });
        if (!response.getCode().equals("200")) {
            throw new RuntimeException(resString);
        }
        if (response.getCode().equals("200")) {
            List<ManageClassBeanTree> myDataManageClass = response.getData();
            List<ManageClassEntity> myList = new ArrayList<>();
            if (myDataManageClass != null && myDataManageClass.size() > 0) {
                getData(myDataManageClass, myList, tenantId);
                Integer rInt = InsertBatch(myList);
                System.out.println("EventManageClassEditTree影响条数" + rInt);
            }
        } else {
            System.out.println("EventManageClassEditTree" + response.getMessage());
        }
    }

    private void getData(List<ManageClassBeanTree> myDataManageClass, List<ManageClassEntity> myList, String tenantId) {
        if (myDataManageClass.size() > 0) {
            for (ManageClassBeanTree tempEntity : myDataManageClass) {
                if (tempEntity.getChildren() == null || tempEntity.getChildren().size() == 0) {
                    ManageClassEntity entity = MyTool.convertBean2Bean(tempEntity, ManageClassEntity.class);
                    entity.setTenant_id(tenantId);
                    myList.add(entity);
                } else getData(tempEntity.getChildren(), myList, tenantId);
            }
        }
    }
}
